﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using DotNet.Common;

namespace CopyFolders
{
    public partial class Form1 : Form
    {
        private WriteLog log = new WriteLog();
        private BackgroundWorker _worker = new BackgroundWorker();

        private int totalNum, currentNum;
        private XmlNodeList _xmlNodeList;
        private bool _isHasException;//记录是否有异常
        private string _targetPath, _path, _fileName;

        public Form1()
        {
            InitializeComponent();
            log.richTextBoxRemote = rtInfo;
        }

        #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。

        /****************************************
         * 函数名称：CopyDir
         * 功能说明：将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
         * 参    数：srcPath:原始路径,aimPath:目标文件夹
         * 调用示列：
         *           string srcPath = Server.MapPath("test/");  
         *           string aimPath = Server.MapPath("test1/");
         *           DotNet.Utilities.FileOperate.CopyDir(srcPath,aimPath);   
        *****************************************/

        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        public void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                    aimPath += Path.DirectorySeparatorChar;
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                    Directory.CreateDirectory(aimPath);
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
                //string[] fileList = Directory.GetFiles(srcPath);
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                //遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件

                    if (Directory.Exists(file))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                        //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }
            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }

        #endregion

        private void btnExcute_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtTargetPath.Text))
            {
                log.LogError("目标路径不能为空！");
                return;
            }
            _targetPath = txtTargetPath.Text.Trim();
            if (_targetPath.Substring(_targetPath.Length - 1) != "\\")
                _targetPath += "\\";
            try
            {
                string flodersPath = chkServerPath.Checked ? "foldersServer.xml" : "folders.xml";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(flodersPath);

                XmlNode xn = xmlDoc.SelectSingleNode("folders");

                // 得到根节点的所有子节点
                _xmlNodeList = xn.ChildNodes;
                totalNum = _xmlNodeList.Count;
                currentNum = 0;

                btnExcute.Enabled = false;
                log.LogMessage("开始复制...", Color.Green, DateTime.Now.ToString("hh:mm:ss"));
                _worker.RunWorkerAsync();
            }
            catch (Exception err)
            {
                log.LogError(err.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _isHasException = false;
            this.txtTargetPath.Text = "N:\\" + DateTime.Now.ToString("yyyyMMdd") + "Foxpro";
            _worker.DoWork += new DoWorkEventHandler(DoWork);
            _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(DoWorkCompleted);
        }

        private void DoWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_isHasException)
                log.LogError("复制文件 " + _fileName + "到 " + _targetPath + "失败！");
            else
                log.LogAppendMsg("复制文件 " + _fileName + "到 " + _targetPath + "成功！");
            currentNum++;
            if (currentNum != totalNum)
            {
                _isHasException = false;
                _worker.RunWorkerAsync();
            }
            else
            {
                log.LogMessage("复制结束", Color.Green, DateTime.Now.ToString("hh:mm:ss"));
                btnExcute.Enabled = true;
            }
        }

        private void DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                XmlNode n = _xmlNodeList[currentNum];
                if (n.NodeType == XmlNodeType.Element)
                {
                    XmlElement element = (XmlElement) n;
                    _path = element.InnerText;
                    _fileName = element.GetAttribute("fileName");

                    CopyDir(_path, _targetPath + _fileName);
                }
            }
            catch (Exception err)
            {
                _isHasException = true;
                log.LogError(err.Message + "***" + _targetPath + "******" + _fileName);
            }
        }
    }
}
